<template>
    <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
      :close-on-click-modal="false" draggable>
      <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
            <el-row :gutter="24">
               <!-- 第一部分 -->
               <template v-if="step === 1">
                    <el-col :span="12" class="mb20">
                      <el-form-item label="模型名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入模型名称"/>
                      </el-form-item>
                    </el-col>

                     <el-col :span="12" class="mb20">
                        <el-form-item label="请求方式" prop="method">
                          <el-select v-model="form.method" placeholder="请选择请求方式">
                              <el-option :key="index"
                                         :label="item.label"
                                         :value="item.value"
                                         v-for="(item, index) in method"></el-option>
                          </el-select>
                        </el-form-item>
                     </el-col>

                      <el-col :span="12" class="mb20">
                          <el-form-item label="请求路径" prop="url">
                            <el-input v-model="form.url" placeholder="请输入请求路径"/>
                          </el-form-item>
                      </el-col>

                      <el-col :span="12" class="mb20">
                          <el-form-item label="组件版本" prop="version">
                            <el-input v-model="form.version" placeholder="请输入组件版本"/>
                          </el-form-item>
                      </el-col>

                       <el-col :span="12" class="mb20">
                        <el-form-item label="请求类型" prop="parameterType">
                            <el-radio-group v-model="form.parameterType">
                                <el-radio value="0" size="large" border>键值对Form</el-radio>
                                <el-radio value="1" size="large" border>requestBody字符串</el-radio>
                            </el-radio-group>
                        </el-form-item>
                       </el-col>
                       <el-col :span="12" class="mb20">
                           <el-form-item label="状态" prop="status">
                               <el-radio-group v-model="form.status">
                                   <el-radio value="0" size="large" border>启用</el-radio>
                                   <el-radio value="1" size="large" border>停用</el-radio>
                               </el-radio-group>
                           </el-form-item>
                       </el-col>
                       <el-col :span="24" class="mb20">
                           <el-form-item label="认证方式" prop="authentication">
                               <el-radio-group v-model="form.authentication">
                                   <el-radio value="0" size="large" border>需要认证(token)</el-radio>
                                   <el-radio value="1" size="large" border>需要认证(appkey)</el-radio>
                                   <el-radio value="2" size="large" border>匿名调用</el-radio>
                               </el-radio-group>
                           </el-form-item>
                       </el-col>
               </template>

               <!-- 第二部分 -->
               <template v-else-if="step === 2">
                    <el-col :span="12" class="mb20">
                      <el-form-item label="绑定服务" prop="serviceId">
                          <el-select v-model="form.serviceId" placeholder="请选择绑定服务">
                              <el-option v-for="option in bindingOptions" :key="option.value" :label="option.label" :value="option.value" />
                          </el-select>
                        </el-form-item>
                    </el-col>
                   <el-col :span="24" class="mb20">
                       <el-tabs v-model="activeTab">
                           <el-tab-pane label="输入参数" name="inputParams">
                               <template v-if="form.parameterType === '0'">
                                   <el-button type="primary" @click="addParameter">新增</el-button>
                                       <el-table :data="form.parameter" style="width: 100%">
                                       <el-table-column type="index" label="序号" width="150" />
                                       <el-table-column label="参数名" width="300">
                                           <template #default="scope">
                                               <el-input v-model="scope.row.name" placeholder="请输入参数名" />
                                           </template>
                                       </el-table-column>
                                       <el-table-column label="参数默认值" width="300">
                                           <template #default="scope">
                                               <el-input v-model="scope.row.defaultValue" placeholder="请输入默认值" />
                                           </template>
                                       </el-table-column>
                                       <el-table-column label="操作" width="130">
                                           <template #default="scope">
                                               <el-button @click="removeParameter(scope.$index)" type="text" size="small">删除</el-button>
                                           </template>
                                       </el-table-column>
                                   </el-table>
                               </template>
                               <template v-else>
                                    <el-input v-model="form.parameters" style="width: 100%" :rows="20" type="textarea" placeholder="请输入header参数"/>
                               </template>
                           </el-tab-pane>
                           <el-tab-pane label="header参数" name="headerParams">
                               <el-button type="primary" @click="addheaderParameter">新增</el-button>
                               <el-table :data="form.header" style="width: 100%">
                                   <el-table-column type="index" label="序号" width="150" />
                                   <el-table-column label="参数名" width="300">
                                       <template #default="scope">
                                           <el-input v-model="scope.row.name" placeholder="请输入参数名" />
                                       </template>
                                   </el-table-column>
                                   <el-table-column label="参数默认值" width="300">
                                       <template #default="scope">
                                           <el-input v-model="scope.row.defaultValue" placeholder="请输入默认值" />
                                       </template>
                                   </el-table-column>
                                   <el-table-column label="操作" width="130">
                                       <template #default="scope">
                                           <el-button @click="removeheaderParameter(scope.$index)" type="text" size="small">删除</el-button>
                                       </template>
                                   </el-table-column>
                               </el-table>
                           </el-tab-pane>
                       </el-tabs>
                   </el-col>
               </template>

            </el-row>
         </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="step === 2" @click="step = 1">上一步</el-button>
          <el-button v-if="step === 1" @click="step = 2">下一步</el-button>
          <el-button @click="visible = false">取消</el-button>
          <el-button v-if="step === 2" type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script setup lang="ts" name="ManagementDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj, servicedata } from '/@/api/model/management'
import { rule } from '/@/utils/validate';
import {onMounted} from "vue";
const emit = defineEmits(['refresh']);

const { method } = useDict('method');

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const activeTab = ref('inputParams'); // 默认显示输入参数页签
const step = ref(1); // 步骤控制变量

// 提交表单数据
const form = reactive({
      id:'',
      sortId: '',
	  name: '',
	  method: '',
	  url: '',
	  version: '',
	  requestType: '',
      authentication: '',
	  status: '',
      serviceId: '',
      parameters: '',
	  parameter: [] as Array<{ name: string, defaultValue: string }>, // 修改为数组
	  header: [] as Array<{ name: string, defaultValue: string }>, // 修改为数组
});

// 定义校验规则
const dataRules = ref({
});

const bindingOptions = ref([]);

// 打开弹窗
const openDialog = (id: string | null, sortId: string) => {
  visible.value = true;
  step.value = 1; // 重置步骤为第一步
  form.id = '';
  form.sortId = sortId; // 设置sortId
  // 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

  // 获取modeManagement信息
  if (id) {
    form.id = id;
    getmodeManagementData(id)
  }
};
onMounted(() => {
    // 调用servicedata接口获取绑定服务数据
    servicedata().then((res: any) => {
        console.log(res.data.records);
        // 将绑定服务数据映射为下拉框选项
        bindingOptions.value = res.data.records.map((item: any) => ({
            label: item.name,
            value: item.id,
        }));
        console.log(bindingOptions)
    }).catch((error: any) => {
        console.error('Failed to fetch binding data:', error);
    });
});
// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
    // 根据parameterType的值来决定是否赋值
    if (form.parameterType === '1') {
        form.parameter = form.parameters; // 如果parameterType等于1，将parameters的值赋给parameter
    } else {
        // 如果parameterType不是1，这里假设你已经有其他逻辑处理form.parameter
        form.parameter = JSON.stringify(form.parameter);
    }
    form.header = JSON.stringify(form.header);
	try {
    loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getmodeManagementData = (id?: string) => {
  // 获取数据
   step.value = 1;
  loading.value = true;
  getObj(id).then((res: any) => {
    Object.assign(form, res.data);
      if (res.data.parameterType === '1') {
          form.parameters = res.data.parameter; // 如果parameterType等于1，将parameter的值赋给parameters
      } else {
          form.parameter = res.data.parameter ? JSON.parse(res.data.parameter) : [];
      }
      form.header = res.data.header ? JSON.parse(res.data.header) : [];
      console.log("测试一下");
  }).finally(() => {
    loading.value = false
  })
};
// 增加参数
const addParameter = () => {
    form.parameter.push({ name: '', defaultValue: '' });
};

// 删除参数
const removeParameter = (index: number) => {
    form.parameter.splice(index, 1);
};

//增加参数
const addheaderParameter = () => {
    form.header.push({ name: '', defaultValue: '' });
};

//删除参数
const removeheaderParameter = (index: number) => {
    form.header.splice(index, 1);
};


// 暴露变量
defineExpose({
  openDialog
});
</script>
